<template>
  <div class="work-weixin" v-if="!loading">
    <slot/>
  </div>
  <van-loading v-else size="24px" class="page-loading">加载中…</van-loading>
</template>
<script>
/**
 * @description 企业微信注册功能组件
 */
import { createNamespacedHelpers, mapState } from 'vuex'
import { getAvailableAPIs, registerAgent, registerCorp } from '@/api/work-weixin'
import { CREATE_SIGNATURE_METHOD } from '@/utils/enums/backlog'
import { getLocalStorage } from '@/utils'
import { handleAuth, isWxBrowser } from '@/utils/work-weixin'

const { mapActions } = createNamespacedHelpers('workWeixin')

const jsApiListCorp = [
  'onHistoryBack',
  'closeWindow',
  'hideAllNonBaseMenuItem',
  'openEnterpriseChat',
  'setClipboardData',
]

const jsApiList = [
  'getCurExternalContact',
  'openEnterpriseChat',
  'getCurExternalChat',
  'openExistedChatWithMsg',
  'getContext',
  'navigateToAddCustomer',
  'sendChatMessage',
  'openUserProfile',
  'previewFile',
  'previewImage',
  'selectEnterpriseContact',
  'selectExternalContact',
  'chooseImage',
  'setClipboardData',
  'shareWechatMessage', // 转发到个人微信
  'shareTimeline', // 转发到微信朋友圈
  'shareToExternalMoments', // 转发到客户朋友圈
  'shareToExternalContact', // 群发到客户群
  'shareAppMessage', // 转发到企业微信会话
  'shareToExternalChat', // 群发到客户群
]

export default {
  name: 'work-weixin',

  data() {
    return {
      loading: true,
      curExtContactId: '', // 当前外部联系人id
      curExtChatId: '', // 当前外部群id
      timestamp: '',
      nonceStr: '',
      signature: ''
    }
  },
  async created() {
    // console.log('wx组件:')
    await this.getConfigIds()
    // console.log('wx:getConfigIds')
    if (isWxBrowser().isWxWork) { // 企业微信验签
      // console.log('开始企业微信验签')
      this.registerCorpAndApp()
    } else if (isWxBrowser().isWx) { // 个人微信验签
      // console.log('个人微信验签')
      this.wxRegister()
    } else {
      this.loading = false
      this.$toast('抱歉，请在微信或者企业微信中打开本应用~')
    }
  },
  computed: {
    ...mapState('workWeixin', {
      permissionList: state => {
        return state.permissionList
      }
    })
  },
  methods: {
    ...mapActions(['createSignatureEnterprise', 'createSignatureApplication', 'verifySignature', 'setEntryEnv', 'setGroupId']),
    gotoErrorPage(tip) {
      this.$router.push({
        name: 'error-page',
        query: {
          tip
        }
      })
    },

    // 获取corpId， 如果没有被authorization包裹，获取不到corpId，需要调用接口设置
    async getConfigIds() {
      const corpId = getLocalStorage('corpId')
      const agentId = getLocalStorage('agentId')
      if (corpId && agentId) {
        return { corpId, agentId }
      } else {
        return await handleAuth()
      }

    },
    // 检查注入企业信息成功，隐藏企微右上角点击后的三个点功能
    checkAvailableAPIs() {
      console.log('checkAvailableAPIs->')
      getAvailableAPIs(jsApiListCorp).then((availableAPIs) => {
        // 隐藏系统自带转发、分享等功能
        availableAPIs.includes('hideAllNonBaseMenuItem') && wx.hideAllNonBaseMenuItem()
        // console.log('getAvailableAPIs->')
        // 在首页后退时直接关闭应用
        wx.onHistoryBack(function () {
          const obj = new URLSearchParams(location.search)
          const closeCondition = obj.get('backCloseWindow') === 'true'
          if (closeCondition) {
            wx.closeWindow()
          }
          // console.log('onHistoryBack->')
          return !closeCondition
        })
      })
    },

    registerCorpAndApp() {
      this.registerQYCorpConfig()
      this.registerQYAgentConfig()
    },

    registerQYCorpConfig() {
      const that = this
      // 注册企业应用信息
      const url = window.location.href
      // console.log('企业url', url)
      return this.createSignatureEnterprise({
        data: {
          type: CREATE_SIGNATURE_METHOD.get('CORP'),
          url
        }
      }).then((res) => {
        console.log('企业:createSignature:res', res)
        const { data, code, message = '注入企业信息失败' } = res
        if (code === 200) {
          that.timestamp = data.timestamp
          that.nonceStr = data.nonceStr
          that.signature = data.signature
          return registerCorp({
            beta: true,
            debug: false,
            appId: getLocalStorage('corpId'),
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: jsApiListCorp
          }).then((resp) => {
            console.log('registerCorp resp', resp)
            this.checkAvailableAPIs()
          }).catch(error => {
            console.log('registerCorp error', error)
            this.gotoErrorPage('获取企业信息失败')
            return error.msssage || '获取企业信息失败'
          })
        } else {
          this.$toast.fail('3333' + message)
        }
      })
    },
    registerQYAgentConfig() {
      const that = this
      // 注入应用信息
      const url = window.location.href
      // console.log('应用url', url)
      return this.createSignatureApplication({
        data: {
          type: CREATE_SIGNATURE_METHOD.get('APP'),
          url
        },
      }).then(res => {
        console.log('应用:createSignature:res', res)
        const { data, code, message = '注入应用信息失败' } = res
        if (code === 200) {
          that.timestamp = data.timestamp
          that.nonceStr = data.nonceStr
          that.signature = data.signature
          return registerAgent({
            corpid: getLocalStorage('corpId'),
            agentid: getLocalStorage('agentId'),
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList
          }).then((resp) => {
            // 判断当前地址是否为[客户详情]路由且无传参userId时
            // 判断当前地址是否为[社群详情]路由且无传参chatId时
            // 判断当前地址是否为[每日sop]路由且无传参chatId时
            console.log('registerAgent resp', resp)
            console.log('看看当前路由及传参:', this.$route.name, '----', this.$route.query.userId, '----', this.$route.query.chatId)
            const judgeEntryCondition = (this.$route.name === 'customer-detail' && !this.$route.query.userId) ||
                (this.$route.name === 'group-detail' && !this.$route.query.chatId) ||
                (this.$route.name === 'dailySop' && !this.$route.query.chatId) ||
                (this.$route.name === 'pendToDo')
            // console.log('judgeEntryCondition:', judgeEntryCondition)
            if (judgeEntryCondition) {
              this.getContextEntry()
            } else {
              this.loading = false
            }
          }).catch(error => {
            console.log('registerAgent error', error)
            this.gotoErrorPage(error.msssage || '获取应用信息签名失败')
            return error.msssage || '获取应用信息签名失败'
          })
        } else {
          this.$toast.fail('44444' + message)
        }
      })
    },
    getContextEntry() {
      // console.log('wx:获取当前入口->getContextEntry')
      const that = this
      wx.invoke('getContext', {}, function (res) {
        console.log('wx:getContext:res', res)
        if (res.err_msg === 'getContext:ok') {
          // entry = res.entry // 返回进入H5页面的入口类型，目前有normal、contact_profile、single_chat_tools、group_chat_tools、chat_attachment
          // shareTicket = res.shareTicket // 可用于调用getShareInfo接口
          if (res.entry === 'single_chat_tools') {
            // 单聊
            that.getCurExternalContact()
          } else if (res.entry === 'group_chat_tools') {
            // 群聊
            that.getCurExternalChat()
          } else {
            console.log('非单聊模式, 业务中处理是否判断，在此可以多扩展，如得到非单聊其它参数需求等等')
          }

          // 通知全局入口判断完毕
          window.postMessage({ msg: 'getContext:ok', entry: res.entry }, window.location.origin)
        } else {
          // 错误处理
          this.gotoErrorPage(res.err_msg)
        }
      })
    },
    getCurExternalContact() {
      // console.log('wx:获取当前外部联系人userid')
      const that = this
      wx.invoke('getCurExternalContact', {}, function (res) {
        console.log('wx:getCurExternalContact:res', res)
        if (res.err_msg === 'getCurExternalContact:ok') {
          that.loading = false
          // userId  = res.userId ; //返回当前外部联系人userId
          // console.log('当前外部联系人userId', res.userId)
          that.curExtContactId = res.userId
          that.exportWXRelatedInfo()
          // 通知全局侧1v1下获取当前外部联系人id完毕
          window.postMessage({
            msg: 'getCurExternalContact:ok',
            entry: 'single_chat_tools',
            id: res.userId
          }, window.location.origin)
        } else {
          // 错误处理
          this.gotoErrorPage(res.err_msg)
        }
      })
    },
    getCurExternalChat() {
      // console.log('获取当前外部群chatId')
      const that = this
      wx.invoke('getCurExternalChat', {}, function (res) {
        console.log('wx:getCurExternalChat:res', res)
        if (res.err_msg === 'getCurExternalChat:ok') {
          that.loading = false
          that.curExtChatId = res.chatId
          that.exportWXRelatedInfo()
          // 通知全局侧群聊下获取当前外部群id完毕
          window.postMessage({
            msg: 'getCurExternalChat:ok',
            entry: 'group_chat_tools',
            id: res.chatId
          }, window.location.origin)
        } else {
          // 错误处理
          this.gotoErrorPage(res.err_msg)
        }
      })
    },
    wxRegister() {
      // 微信页面验证签名
      this.loading = false
      const url = window.location.href
      const params = {
        url
      }
      this.verifySignature({ params }).then((res) => {
        console.log('wx:verifySignature:res', res)
        const { statusCode, data, message = '服务异常，请稍后重试' } = res
        if (statusCode === 200) {
          // eslint-disable-next-line no-undef
          jWeixin.config({
            debug: false, // 需要调试的时候开启
            appId: getLocalStorage('appId'),
            timestamp: data.timestamp,
            nonceStr: data.nonceStr,
            signature: data.signature,
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'updateAppMessageShareData']
          })
          // eslint-disable-next-line no-undef
          jWeixin.error(function (res) {
            console.log('config', res)
          })
        } else {
          this.$toast.fail('55555' + message)
        }
      })
    },
    exportWXRelatedInfo() {
      this.$emit('exportWxInfo', {
        curExtContactId: this.curExtContactId,
        curExtChatId: this.curExtChatId,
        timestamp: this.timestamp,
        nonceStr: this.nonceStr,
        signature: this.signature
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
